/*
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 *
 * Copyright @2008 the original author or authors.
 */
package com.bluestone.core;

import java.util.ArrayList;
import java.util.HashMap;

import com.bluestone.util.Util;

/**
 * CallFuntionAction can execute a function.
 * @author <a href="mailto:bluesotne.master@gmail.com">daniel.q</a>
 */
public class CallFunctionAction extends Action {

	/**
	 * 
	 * @param type String that defines the type of the action.
	 * @param target String that defines the name of the function.
	 * @param value String that defines the parameters of the function.
	 * @param delay String that defines the delay time after the action finished.
	 * @param offset String that defines the offset of the graphical elements.
	 */
	public CallFunctionAction(String type, String target, String value, String delay, String offset) {
		super(type, target, value, delay, offset);
	}
	/**
	 * This action can execute a function.
	 * @return false if the target is not exsit or if the function execute failure.
	 */
	@Override
	public boolean execute(){
		
		Function function = Util.getCurrentProject().searchFunction(target);
		if(function == null){
			Util.error(Util.ERROR1+target);
			return false;
		}
		
		HashMap paras = new HashMap();		
		String [] tokens = value.split("[,=]");
		for(int i=0; i< tokens.length ; i=i+2){
			paras.put(tokens[i],tokens[i+1]);
		}
		
		ArrayList actions = function.compile(paras);
				
		for(int i=0; i< actions.size(); i++){
			Action action = (Action)actions.get(i);
			if(!action.isValid()){
				continue;
			}			
			action.setParent(this.parent);
			boolean flag = action.execute();
			Util.info("run " + action.toString() + "-->" + flag);			
			if(!flag){
				Util.warn("run " + action.toString() + "-->" + flag);				
				return false;
			}
		}

		if (delay != null && delay.length() > 0) {
			robot.delay(Util.getDelayTime(Integer.parseInt(delay)));
		} else {
			robot.delay(Util.getDelayTime(Util.CALLFUNCTIONDELAY));
		}		
		return true;
	}

}
